package com.zhg.videorecord.collect;

/**
 * desc:  todo
 * author: ZHG
 * date: 2019/11/22
 */
public class CameraContainer {
    /*private int VIDEO_WIDTH;
    private int VIDEO_HEIGHT;
    private Camera camera;

    private Camera.Parameters mParameters = null;
    private int mCameraId;
    private int mFrameRate;
    protected SurfaceHolder mSurfaceHolder;
    private boolean mSurfaceCreated;
    public interface OnPreviewCallback{
         void onPreviewFrame(byte[] bytes, Camera camera);
    }
    public void setOnOnPreviewCallback(OnPreviewCallback callback){
        this.mPreviewCallback=callback;
    }
    private OnPreviewCallback mPreviewCallback;
    public CameraContainer(OnPreviewCallback previewCallback) {
        this.mPreviewCallback=previewCallback;
    }
    public void startPreview(){
        try {
            camera = Camera.open(mCameraId);
        }catch (Exception e){
            // throw new Exception("拍摄权限被禁用或被其他程序占用, 请确认后再录制");
        }
        boolean mHasPermission = hasPermission();
        if (!mHasPermission) {
           Log.e("","拍摄权限被禁用或被其他程序占用, 请确认后再录制");
        }
        //设置摄像头参数
        prepareCameraParaments();
        camera.setParameters(mParameters);
        setPreviewCallback();
        camera.startPreview();
        onStartPreviewSuccess();
        if (mOnPreparedListener != null)
            mOnPreparedListener.onPrepared();
    }

    *//**
     * 停止预览
     *//*
    public void stopPreview() {
        if (camera != null) {
            try {
                camera.stopPreview();
                camera.setPreviewCallback(null);
                // camera.lock();
                camera.release();
            } catch (Exception e) {
                Log.e("jianxi", "stopPreview...");
            }
            camera = null;
        }
        mStartPreview = false;
    }

    *//**
     * 释放资源
     *//*
    public void release() {
        stopAllRecord();
        // 停止视频预览
        stopPreview();
        // 停止音频录制
        if (mAudioRecorder != null) {
            mAudioRecorder.interrupt();
            mAudioRecorder = null;
        }

        mSurfaceHolder = null;
        mPrepared = false;
        mSurfaceCreated = false;
    }

    *//**
     * 预览调用成功，子类可以做一些操作
     *//*
    protected void onStartPreviewSuccess() {

    }

    *//**
     * 设置预览输出SurfaceHolder
     *
     * @param sh
     *//*
    @SuppressWarnings("deprecation")
    public void setSurfaceHolder(SurfaceHolder sh) {
        if (sh != null) {
            sh.addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder surfaceHolder) {
                    mSurfaceHolder = surfaceHolder;
                    mSurfaceCreated = true;
                    if (mPrepared && !mStartPreview) {
                        startPreview();
                    }
                }

                @Override
                public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                    mSurfaceHolder = surfaceHolder;
                }

                @Override
                public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                    mSurfaceHolder = null;
                    mSurfaceCreated = false;
                }
            });
            if (!DeviceUtils.hasHoneycomb()) {
                sh.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            }
        }
    }
    *//**
     * 测试PreviewFrame回调次数，时间1分钟
     *//*
    public void testPreviewFrameCallCount() {
        new CountDownTimer(1 * 60 * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                android.util.Log.e("[Vitamio Recorder]", "testFrameRate..." + mPreviewFrameCallCount);
                mPreviewFrameCallCount = 0;
            }

            @Override
            public void onFinish() {

            }

        }.start();
    }

    *//**
     * 设置回调
     *//*
    private void setPreviewCallback() {
        Camera.Size size = mParameters.getPreviewSize();
        final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] bytes, Camera camera) {
                //回收缓存，下次仍然会使用，所以不需要再开辟新的缓存，达到优化的目的
                mPreviewCallback.onPreviewFrame(bytes,camera);
                camera.addCallbackBuffer(bytes);
            }
        };
        if (size != null) {
            //一帧预览图大小，width * height *ImageFormat.getBitsPerPixel(ImageFormat.NV21) / 8，
            //即w*h*1.5，nv21 一个像素需要12bit/8=1.5byte存储
            int buffSize = size.width * size.height * 3/2;
            try {
                // ??
                camera.addCallbackBuffer(new byte[buffSize]);
                camera.addCallbackBuffer(new byte[buffSize]);
                //增加buffer
                camera.addCallbackBuffer(new byte[buffSize]);
                //启动预览，每产生一帧都会回调onPreviewFrame()，但每一帧的数据都是一块新的内存区域会造成频繁的 GC
                //camera.setPreviewCallback()
                //内每一帧的 data 就会复用同一块缓冲区域，data 对象没有改变，但是 data 数据的内容改变了，
                // 并且该回调不会返回每一帧的数据，而是在重新调用 addCallbackBuffer 之后才会继续回调
                camera.setPreviewCallbackWithBuffer(previewCallback);
            } catch (OutOfMemoryError e) {
                android.util.Log.e("jianxi", "startPreview...setPreviewCallback...", e);
            }
            android.util.Log.e("jianxi", "startPreview...setPreviewCallbackWithBuffer...width:" + size.width + " height:" + size.height);
        } else {
            camera.setPreviewCallback(previewCallback);
        }
    }
    private boolean hasPermission() {
        boolean mHasPermission = true;
        if (null == camera) {
            mHasPermission = false;
        } else {
            try {
                Class<? extends Camera> class1 = camera.getClass();
                Field filed = class1.getDeclaredField("mHasPermission");
                if (null != filed) {
                    filed.setAccessible(true);
                    mHasPermission = (Boolean) filed.get(camera);
                }
            } catch (Exception e1) {
            }
        }
        return mHasPermission;
    }
    *//**
     * 预处理一些拍摄参数
     * 注意：自动对焦参数cam_mode和cam-mode可能有些设备不支持，导致视频画面变形，需要判断一下，已知有"GT-N7100", "GT-I9308"会存在这个问题
     *//*
    @SuppressWarnings("deprecation")
    protected void prepareCameraParaments() {
        mParameters = camera.getParameters();
        if (mParameters == null) {
            return;
        }
        //获取当前设备支持的帧率
        List<Integer> rates = mParameters.getSupportedPreviewFrameRates();
        mFrameRate=fitPreviewFrameRates(rates,mFrameRate);
        mParameters.setPreviewFrameRate(mFrameRate);
        // mParameters.setPreviewFpsRange(15 * 1000, 20 * 1000);

        //设置预览尺寸
        List<Camera.Size> supportedPreviewSizes = mParameters.getSupportedPreviewSizes();
        if (checkPreviewSize(supportedPreviewSizes, VIDEO_WIDTH, VIDEO_WIDTH)){
            mParameters.setPreviewSize(VIDEO_WIDTH, VIDEO_WIDTH);
        }else {
            VIDEO_WIDTH =supportedPreviewSizes.get(0).width;
            VIDEO_HEIGHT =supportedPreviewSizes.get(0).height;
            android.util.Log.e(getClass().getSimpleName(), "未找到对应宽高，已从支持值中设置为"+ VIDEO_WIDTH +","+ VIDEO_HEIGHT);
        }
        mParameters.setPreviewSize(VIDEO_WIDTH, VIDEO_HEIGHT);

        //获取支持的色彩空间格式 当前设备(rk3288)支持 yv12和nv21
        List<Integer> previewFormats = mParameters.getSupportedPreviewFormats();
        mParameters.setPreviewFormat(ImageFormat.NV21);

        //设置自动连续对焦
        String mode = getAutoFocusMode();
        if (StringUtils.isNotEmpty(mode)) {
            mParameters.setFocusMode(mode);
        }
        //人像模式
        // checkPortraitMode();
        //白平衡
        if (isSupported(mParameters.getSupportedWhiteBalance(), "auto")) {
            mParameters.setWhiteBalance("auto");
        }

        //是否支持视频防抖
        if ("true".equals(mParameters.get("video-stabilization-supported"))) {
            mParameters.set("video-stabilization", "true");
        }

        //		mParameters.set("recording-hint", "false");
        //
        //		mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        if (!DeviceUtils.isDevice("GT-N7100", "GT-I9308", "GT-I9300")) {
            mParameters.set("cam_mode", 1);
            mParameters.set("cam-mode", 1);
        }
    }

    *//**
     * 设置人像模式，用来拍摄人物相片，如证件照。数码相机会把光圈调到最大，做出浅景深的效果。
     * 而有些相机还会使用能够表现更强肤色效果的色调、对比度或柔化效果进行拍摄，以突出人像主体。
     *//*
    private void checkPortraitMode() {
        if (mCameraId == Camera.CameraInfo.CAMERA_FACING_FRONT &&
                isSupported(mParameters.getSupportedSceneModes(), Camera.Parameters.SCENE_MODE_PORTRAIT)) {
            mParameters.setSceneMode(Camera.Parameters.SCENE_MODE_PORTRAIT);
        }
    }
    private int fitPreviewFrameRates(List<Integer> rates,int rate){
        if (rates != null) {
            if (rates.contains(rate)) {
               return rate;
            } else {
                boolean findFrame = false;
                Collections.sort(rates);
                for (int i = rates.size() - 1; i >= 0; i--) {
                    if (rates.get(i) <= rate) {
                        mFrameRate = rates.get(i);
                        findFrame = true;
                        break;
                    }
                }
                if (!findFrame) {
                   return mFrameRate = rates.get(0);
                }
            }
        }
        return rate;
    }

    private boolean checkPreviewSize(List<Camera.Size> supportedPreviewSizes, int previewWidth, int previewHeight){
        //	获取支持的尺寸
        boolean isSupportPreviewSize = false;
        for (Camera.Size size : supportedPreviewSizes) {
            if (previewWidth == size.width && previewHeight == size.height) {
                isSupportPreviewSize = true;
                break;
            }
        }
        return isSupportPreviewSize;
    }
    *//**
     * 检测是否支持指定特性
     *//**//*
    private boolean isSupported(List<String> list, String key) {
        return list != null && list.contains(key);
    }

    /**
     * 连续自动对焦
     *//*
    private String getAutoFocusMode() {
        if (mParameters != null) {
            //持续对焦是指当场景发生变化时，相机会主动去调节焦距来达到被拍摄的物体始终是清晰的状态。
            List<String> focusModes = mParameters.getSupportedFocusModes();
            if ((Build.MODEL.startsWith("GT-I950") || Build.MODEL.endsWith("SCH-I959") || Build.MODEL.endsWith("MEIZU MX3")) && isSupported(focusModes, "continuous-picture")) {
                return "continuous-picture";
            } else if (isSupported(focusModes, "continuous-video")) {
                return "continuous-video";
            } else if (isSupported(focusModes, "auto")) {
                return "auto";
            }
        }
        return null;
    }

    *//**
     * 是否支持前置摄像头
     *//*
    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public  boolean isSupportFrontCamera() {
        if (!DeviceUtils.hasGingerbread()) {
            return false;
        }
        int numberOfCameras = Camera.getNumberOfCameras();
        if (2 == numberOfCameras) {
            return true;
        }
        return false;
    }

    *//**
     * 自动对焦
     *
     * @param cb
     * @return
     *//*
    public boolean autoFocus(Camera.AutoFocusCallback cb) {
        if (camera != null) {
            try {
                camera.cancelAutoFocus();

                if (mParameters != null) {
                    String mode = getAutoFocusMode();
                    if (StringUtils.isNotEmpty(mode)) {
                        mParameters.setFocusMode(mode);
                        camera.setParameters(mParameters);
                    }
                }
                camera.autoFocus(cb);
                return true;
            } catch (Exception e) {
                if (mOnErrorListener != null) {
                    mOnErrorListener.onVideoError(MEDIA_ERROR_CAMERA_AUTO_FOCUS, 0);
                }
                Log.e("jianxi", "autoFocus", e);

            }
        }
        return false;
    }
    *//**
     * 手动对焦
     *
     * @param focusAreas 对焦区域
     * @return
     *//*
    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public boolean manualFocus(Camera.AutoFocusCallback cb, List<Camera.Area> focusAreas) {
        if (camera != null && focusAreas != null && mParameters != null && DeviceUtils.hasICS()) {
            try {
                camera.cancelAutoFocus();
                // getMaxNumFocusAreas检测设备是否支持
                if (mParameters.getMaxNumFocusAreas() > 0) {
                    // mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);//
                    // Macro(close-up) focus mode
                    mParameters.setFocusAreas(focusAreas);
                }

                if (mParameters.getMaxNumMeteringAreas() > 0)
                    mParameters.setMeteringAreas(focusAreas);

                mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
                camera.setParameters(mParameters);
                camera.autoFocus(cb);
                return true;
            } catch (Exception e) {
                if (mOnErrorListener != null) {
                    mOnErrorListener.onVideoError(MEDIA_ERROR_CAMERA_AUTO_FOCUS, 0);
                }
                if (e != null) {
                    android.util.Log.e("jianxi", "autoFocus", e);
                }
            }
        }
        return false;
    }

    *//**
     * 切换闪关灯，默认关闭
     *//*
    public boolean toggleFlashMode() {
        if (mParameters != null) {
            try {
                final String mode = mParameters.getFlashMode();
                if (TextUtils.isEmpty(mode) || Camera.Parameters.FLASH_MODE_OFF.equals(mode)) {
                    setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                } else {
                    setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                }
                return true;
            } catch (Exception e) {
                android.util.Log.e("jianxi", "toggleFlashMode", e);
            }
        }
        return false;
    }

    *//**
     * 设置闪光灯
     *
     * @param value
     *//*
    private boolean setFlashMode(String value) {
        if (mParameters != null && camera != null) {
            try {
                if (Camera.Parameters.FLASH_MODE_TORCH.equals(value) || Camera.Parameters.FLASH_MODE_OFF.equals(value)) {
                    mParameters.setFlashMode(value);
                    camera.setParameters(mParameters);
                }
                return true;
            } catch (Exception e) {
                android.util.Log.e("jianxi", "setFlashMode", e);
            }
        }
        return false;
    }
*/
}
